<template>
  <view class="p-20px">
    <view class="card toast-box">
      <view class="text-center absolute transform -translate-x-1_2 -translate-y-1_2 top-0 left-1_2">
        <button class="inline-block bg-transparent rounded-full p-0" open-type="chooseAvatar"
                @chooseavatar="handlerHeadChoose">
          <u-avatar size="80px" :src="userInfo.header"/>
        </button>
      </view>
      <view class="mb-10px mt-40px">
        <label class="inline-block align-middle">用户昵称：</label>
        <input class="border-b-1px border-#efefef inline-block align-middle" v-model="userInfo.userName" type="nickname"
               placeholder="请输入你的用户名"/>
      </view>
      <view class="mb-20px">
        <label class="inline-block align-middle">学校：</label>
        <view class="inline-block align-middle" @click="handlerSelectSchoolClick">
          <label v-if="selectSchool?.name">{{ selectSchool?.name }}</label>
          <label v-else class="text-blue-500">点击选择学校</label>
        </view>
      </view>
      <u-button type="success" class="mt-20px" @click="handlerConfirm">确认</u-button>
    </view>
  </view>
  <u-toast ref="utoast"/>
  <u-popup :show="schoolPopupShow" overlay @close="close" @open="open">
    <view>
      <view class="flex p-10px">
        <u-search class="w-full" :show-action="false" placeholder="输入学校名称" v-model="schoolFilterParam.name" @change="handlerSchoolNameInput"/>
      </view>
      <u-list height="280px" @scrolltolower="handlerScrollend" :scroll-top="schoolFilterParam.scrollTop" scroll-with-animation>
        <template :key="index" v-for="(item, index) in schoolList">
          <u-list-item>
            <view :class="{'active-item': item.sid === selectSchool?.sid}" class="p-10px border-bottom-1px border-slide border-[rgba(0,0,0,.2)]" @click="handlerSchoolItemClick(item)">
              {{ item.name }}
            </view>
          </u-list-item>
        </template>
      </u-list>
    </view>
  </u-popup>
</template>

<script lang="ts" setup>
import userStore from '@/store/user'
import type {AccountImportBody} from "@/api/im";
import { postAccountImportRes } from '@/api/im'
import {login} from '@/utils/IM'
import {reactive, ref} from "vue";
import UButton from "@/uni_modules/uview-plus/components/u-button/u-button.vue";
import type {School} from "@/api/book";
import {saveUserInfo} from "@/api/user";
import UAvatar from "@/uni_modules/uview-plus/components/u-avatar/u-avatar.vue";
import UToast from "@/uni_modules/uview-plus/components/u-toast/u-toast.vue";
import UPopup from "@/uni_modules/uview-plus/components/u-popup/u-popup.vue";
import {getSchoolList} from "@/api/school";
import UList from "@/uni_modules/uview-plus/components/u-list/u-list.vue";
import UListItem from "@/uni_modules/uview-plus/components/u-list-item/u-list-item.vue";
import { debounce } from '@/utils/debounce.js'
import USearch from "@/uni_modules/uview-plus/components/u-search/u-search.vue";
// 学校选择弹窗显示状态
const schoolPopupShow = ref<boolean>(false)
const close = () => {
  schoolPopupShow.value = false
}
const open = () => {
  schoolPopupShow.value = true
}
// 当前获取学校列表的过滤参数
const schoolFilterParam = reactive({
  name: "",
  area: [],
  pageNum: 1,
  pageSize: 30,
  total: 0,
  scrollTop: 0
})
const handlerSchoolNameInput = () => {
  schoolFilterParam.pageNum = 1
  schoolFilterParam.total = 0
  schoolFilterParam.scrollTop = Math.random()
  fnGetSchoolList()
}
const handlerScrollend = () => {
  schoolFilterParam.pageNum ++
  fnGetSchoolList(true)
}
// 学校列表数据
const schoolList = ref<School[]>([])
// 获取学校列表信息
const fnGetSchoolList = async (isPush?: boolean) => {
  const param = {
    name: schoolFilterParam.name,
    province: schoolFilterParam.area[0] || "",
    city: schoolFilterParam.area[1] || "",
    pageNum: schoolFilterParam.pageNum,
    pageSize: schoolFilterParam.pageSize
  }
  const data = await getSchoolList(param);
  schoolFilterParam.total = data.data.total
  if(isPush){
    schoolList.value.push(...data.data.records)
  }else{
    schoolList.value = data.data.records
  }
}
fnGetSchoolList()
const handlerSchoolItemClick = (item: School) => {
  selectSchool.value = item
  closeSchoolPopup()
}
// 地址选择更改事件
const areaChange = () => {
  fnGetSchoolList()
}
const closeSchoolPopup = () => {
  // 重置搜索框的文字
  schoolFilterParam.name = ""
  // 重置地区参数
  schoolFilterParam.area = []
  // 关闭弹窗
  schoolPopupShow.value = false
}
// 当前选中的学校
const selectSchool = ref<School | null>(null)

const user = userStore()
// 表单对象
const utoast = ref<UToast | null>(null)
// 表单输入内容
const userInfo = reactive<{
  userName: string
  header: string
  school: School | null
}>({
  userName: '',
  header: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
  school: null
})
const handlerHeadChoose = (e) => {
  userInfo.header = e.detail.avatarUrl
}
// 选择学校按钮点击事件
const handlerSelectSchoolClick = () => {
  schoolPopupShow.value = true
  // uni.navigateTo({
  //   url: '/pages/schoolSelect/index'
  // })
}
const fnSelectSchool = (data: School) => {
  userInfo.school = data
}

const fnFirstLogin = async (userId: string, nick: string, faceUrl: string) => {
  const formData: AccountImportBody = {
    UserID: userId,
    Nick: nick,
    FaceUrl: faceUrl
  }
  const data = await postAccountImportRes(formData)
  if (data.ActionStatus === 'OK') {
    // 登录
    login(userId)
  }
}
// 确认按钮点击事件
const handlerConfirm = async () => {
  if(!selectSchool?.value){
    utoast.value?.show({
      type: 'default',
      message: '请选择你的高校'
    })
    return Promise.reject(new Error('未选择高校'))
  }
  // 表单校验通过
  const userData = await saveUserInfo(user.userInfo?.uId, {name: userInfo.userName, headUrl: userInfo.header, sid: selectSchool.value?.sid})
  user.saveUserInfo(userData.data)
  await fnFirstLogin(user.userInfo?.uId?.toString?.(), userInfo.userName, userInfo.header)
  // 返回上一个页面
  uni.navigateBack()
}

defineExpose({fnSelectSchool})
</script>

<style scoped lang="scss">
.toast-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
}
.active-item{
  color: #3c9cff;
}
</style>